const fs = require('fs-extra');
const path = require('path');
const config = require('./config.json');

function padNum(num, n) {
  return num.toString().padStart(n, '0');
}

function currentDate() {
  const d = new Date();
  return `${d.getFullYear()}-${padNum(d.getMonth() + 1, 2)}-${padNum(d.getDate(), 2)}`;
}

function getConfigPath(dirName) {
  const d = global.config.path[dirName] || '';
  return d.replace(/<date>/, currentDate());
}

function doesFileExist(filePath) {
  return new Promise((resolve) => fs.access(filePath, fs.constants.F_OK, (err) => resolve(!err)));
}

async function clearExpiredCache() {
  const cachePath = config.path.cacheDir;
  if (!await doesFileExist(cachePath)) {
    return Promise.resolve();
  }
  const dirs = await fs.readdir(cachePath);
  const now = new Date();
  return Promise.all(dirs.map((name) => {
    if (now - new Date(name) < 48 * 3600000) {
      return Promise.resolve();
    }
    return fs.remove(path.join(cachePath, name));
  }));
}

async function clearCache() {
  const cachePath = config.path.cacheDir;
  if (!await doesFileExist(cachePath)) {
    return Promise.resolve();
  }
  const dirs = await fs.readdir(cachePath);
  return Promise.all(dirs.map((name) => fs.remove(path.join(cachePath, name))));
}

function getCodeInstrumentationDir() {
  return config.path.codeInstrumentationDir;
}

module.exports = {
  getCodeInstrumentationDir,
  getConfigPath,
  clearExpiredCache,
  clearCache,
};
